﻿using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using ST.Buz.Base.Entity;
using ST.Buz.Base.Enums;
using ST.Buz.Base.ViewModel;
using ST.Buz.Service;
using ST.Common.Data;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using ST.Common.Util.Text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;

namespace ST.Buz.Web.Controllers
{
	[Route("sys/common")]
	public class SysController : MyBaseController
	{
		/// <summary>
		/// 上传文件大小限制
		/// </summary>
		private static int MAX_FILE_SIZE = 10485760;//10M
		private readonly IServiceSysEnumCode serviceSysEnumCode;
		public SysController(ILogger<SysController> _logger, 
			IServiceSysEnumCode _serviceSysEnumCode)
			: base(_logger)
		{
			this.serviceSysEnumCode = _serviceSysEnumCode;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		[HttpGet("index")]
		[ValidateSession]
		public IActionResult Index()
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				ViewBag.ServiceCode = "4EA7FD46F1";
				return View();
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "打开页面出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		[HttpGet("config")]
		[ValidateSession]
		public IActionResult Config()
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				ViewBag.CurrentMenu = "C065EF8575";//子菜单，需要修改与AdminMenuViewComponent一致
				return View();
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "打开页面出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		[HttpGet("icons")]
		public IActionResult Icons(string callback)
		{
			try
			{
				ViewData["callback"] = string.IsNullOrEmpty(callback) ? "popIconCallback" : callback;
				return View();
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "打开页面出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		public IActionResult Browser()
		{
			return View();
		}

		[Route("error404")]
		public IActionResult Error404()
		{
			return View();
		}

		[Route("error500")]
		public IActionResult Error500()
		{
			return View();
		}

		[Route("error401")]
		public IActionResult Error401()
		{
			return View();
		}

		[HttpGet("errorreport")]
		public JsonResult ErrorReport()
		{
			try
			{
				var feature = HttpContext.Features.Get<IExceptionHandlerFeature>();
				var error = feature?.Error;
				logger.LogError(error, error.Message);
				return new JsonResultBase(false, error.Message, (int)HttpStatusCode.InternalServerError);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, ex.StatusCode);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.InternalServerError);
			}
			catch (ArgumentException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.InternalServerError);
			}
		}

		[HttpGet("dict")]
		public JsonResult GetDict(string code)
		{
			switch (code)
			{
				//case "001":
				//	{
				//		JsonResultBase ret = new JsonResultBase(GetEnums(typeof(BuzStateEnum)));
				//		return ret;
				//	}
				//case "002":
				//	{
				//		JsonResultBase ret = new JsonResultBase(GetEnums(typeof(QJFSEnum)));
				//		return ret;
				//	}
				default:
					{
						return new JsonResultBase(false, "参数代码有误", (int)HttpStatusCode.BadRequest);
					}
			}
		}

		[HttpPost("upload")]
		public ActionResult Upload()
		{
			//Response.Headers.Add("Access-Control-Allow-Origin", "*");

			string callback = Request.Form["callback"];
			try
			{
				string fileType = Request.Form["type"];
				string[] fileTypes = (string.IsNullOrEmpty(fileType) ? "" : fileType).Split('|');
				List<string> validExtensions = null;
				if (fileTypes == null || fileTypes.Length == 0)
				{
					validExtensions = new List<string>() { ".jpg", ".jpeg", ".bmp", ".png", ".gif", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".wps", ".pdf", ".7z", ".zip", ".rar" };
				}
				else
				{
					validExtensions = new List<string>();

					if (Array.IndexOf(fileTypes, "image") >= 0)
					{
						validExtensions.AddRange(new string[] { ".jpg", ".jpeg", ".bmp", ".png", ".gif" });
					}
					if (Array.IndexOf(fileTypes, "word") >= 0)
					{
						validExtensions.AddRange(new string[] { ".doc", ".docx", ".wps" });
					}
					if (Array.IndexOf(fileTypes, "excel") >= 0)
					{
						validExtensions.AddRange(new string[] { ".xls", ".xlsx" });
					}
					if (Array.IndexOf(fileTypes, "ppt") >= 0)
					{
						validExtensions.AddRange(new string[] { ".ppt", ".pptx" });
					}
					if (Array.IndexOf(fileTypes, "zip") >= 0)
					{
						validExtensions.AddRange(new string[] { ".7z", ".zip", ".rar" });
					}
					if (Array.IndexOf(fileTypes, "pdf") >= 0)
					{
						validExtensions.AddRange(new string[] { ".pdf" });
					}
				}
				if (Request.Form.Files == null || Request.Form.Files.Count == 0)
				{
					throw new BuzException("请选择要上传的文件");
				}
				IFormFile file = Request.Form.Files[0];
				if (file.Length == 0)
				{
					throw new BuzException("不能上传空文件");
				}
				string fileExt = Path.GetExtension(file.FileName);
				if (!validExtensions.Contains(fileExt))
				{
					throw new BuzException("不支持该文件格式");
				}
				if (file.Length > MAX_FILE_SIZE)
				{
					throw new BuzException("文件大小超出限制（" + MAX_FILE_SIZE + "）");
				}
				UserSession userSession = GetSessionFromRequest();

				string fileName = IDGenerator.NextRand32(userSession.SessionType, userSession.SessionID) + fileExt;
				string fileUrl = "/upload/" + fileName;
				string fileDir = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/upload");
				if (!Directory.Exists(fileDir))
				{
					Directory.CreateDirectory(fileDir);
				}
				string filePath = Path.Combine(fileDir, fileName);
				using (FileStream fs = new FileStream(filePath, FileMode.CreateNew))
				{
					file.CopyTo(fs);
				}
				SysAttachmentDetail info = new SysAttachmentDetail();
				info.url = fileUrl;
				info.size = (int)file.Length;
				info.title = file.FileName;
				info.type = fileType;
				info.infoid = TextHelper.GetInt(Request.Form["infoid"]);
				info.tblid = TextHelper.GetInt(Request.Form["tblid"]);
				if (string.IsNullOrEmpty(callback))
				{
					JsonResultBase ret = new JsonResultBase(info);
					ret.StatusCode = (int)HttpStatusCode.Created;
					return ret;
				}
				else
				{
					return Content(callback + "(" + Json(info) + ")");
				}
			}
			catch (AuthException ex)
			{
				logger.LogError(ex, "解析请求头部验证信息出错");
				if (string.IsNullOrEmpty(callback))
				{
					return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
				}
				else
				{
					ResultData ret = new ResultData(false, ex.Message);
					return Content(callback + "(" + Json(ret) + ")");
				}
			}
			catch (BuzException ex)
			{
				if (string.IsNullOrEmpty(callback))
				{
					return new JsonResultBase(false, ex.Message);
				}
				else
				{
					ResultData ret = new ResultData(false, ex.Message);
					return Content(callback + "(" + Json(ret) + ")");
				}
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "上传文件出错");
				if (string.IsNullOrEmpty(callback))
				{
					return new JsonResultBase(false, "上传失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message), (int)HttpStatusCode.InternalServerError);
				}
				else
				{
					ResultData ret = new ResultData(false, "上传失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
					return Content(callback + "(" + Json(ret) + ")");
				}
			}
		}

		[HttpGet("upload")]
		public ActionResult Upload(string callback, string infoid, string tblid)
		{
			ViewData["callback"] = string.IsNullOrEmpty(callback) ? "uploadCallback" : callback;
			ViewData["infoid"] = infoid;
			ViewData["tblid"] = tblid;
			return View();
		}

		[HttpGet("uploadm")]
		public ActionResult UploadMini(string callback, string type, string size)
		{
			ViewData["callback"] = string.IsNullOrEmpty(callback) ? "uploadCallback" : callback;
			int maxSize = TextHelper.GetInt(size);
			ViewBag.MaxFileSizeOfM = maxSize > 0 ? maxSize : MAX_FILE_SIZE / 1024;
			string imageThumbnails = "false";
			switch (type)
			{
				case "image":
					ViewBag.Exts = ".bmp,.jpg,.jpeg,.gif,.png";
					imageThumbnails = "true";
					break;
				case "word":
					ViewBag.Exts = ".doc,.docx,.wps";
					break;
				case "excel":
					ViewBag.Exts = ".xls,.xlsx";
					break;
				case "ppt":
					ViewBag.Exts = ".ppt,.pptx";
					break;
				case "zip":
					ViewBag.Exts = ".7z,.zip,.rar";
					break;
				case "pdf":
					ViewBag.Exts = ".pdf";
					break;
				case "file":
				default:
					ViewBag.Exts = ".bmp,.jpg,.jpeg,.gif,.png,.doc,.docx,.xls,.xlsx,.wps,.pdf,.7z,.zip,.rar";
					break;
			}
			ViewData["type"] = type;
			ViewBag.ImageThumbnails = imageThumbnails;
			return View();
		}

		[HttpGet("upload2bind")]
		public ActionResult UploadToBind(string callback, string infoid, string tblid)
		{
			ViewData["callback"] = string.IsNullOrEmpty(callback) ? "uploadCallback" : callback;
			ViewData["infoid"] = infoid;
			ViewData["tblid"] = tblid;
			return View();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		[ValidateSession]
		[HttpGet("dbbackuplist")]
		public IActionResult DBBackupList(string title)
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				ViewBag.CurrentMenu = "FB13E59B9E";//子菜单，需要修改
				ViewBag.Title = string.IsNullOrEmpty(title) ? "数据库备份列表" : title;

				return View();
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "打开页面出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 生成二维码
		/// </summary>
		/// <returns></returns>
		[HttpPost("genscanqr")]
		public IActionResult GenScanQR()
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				var scanUrl = string.Empty;
				//var scanUrl = Request.Scheme + "://wx.sqcdrj.com/pmis/#/login?nc=" + DateTime.Now.Ticks + "&apiurl=";
				var codeQR = serviceSysEnumCode.GetByCode("GiftCardNotifyBindUrl", sessionCurrent);
				if (codeQR != null)
				{
					scanUrl = codeQR.Value;
				}
				var url = scanUrl.Replace("{url}", Request.GetRequestDomainBase(true)).Replace("{uid}", sessionCurrent.UserID.ToString()).Replace("{urlencode}", WebUtility.UrlEncode(Request.GetRequestDomainBase(true)));
				return new JsonResultBase(url);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}
	}
}